from asyncio import sleep, get_event_loop
from os import system, getcwd
from os.path import join
from Config import Config
from api import get_ip, get_blance
from sys import argv
from tool import check_userdir_alive

from pyppeteer import launch
from fake_useragent import UserAgent

count = 0


async def new_page():
    browser = await launch(
        {
            'headless': False,
            'args': [
                '--no-sandbox',
                f"--window-size=1920*1080",
                f"--proxy-server={get_ip()}",  # 挂代理
                "--disable-infobars"
            ],
            'dumpio': True,
            "userDataDir": join(getcwd(), "temp")
        }
    )

    page = await browser.newPage()

    page.setDefaultNavigationTimeout(60)

    await page.authenticate({'username': f'{Config.account}', 'password': f'{Config.password}'})

    await page.setUserAgent(UserAgent().random)

    await page.evaluateOnNewDocument('''
            () => {
                Object.defineProperty(navigator, 'webdriver', {
                get: () => false
                })
            }
        ''')

    await page.evaluateOnNewDocument('''
() =>{ window.navigator.chrome = { runtime: {},  }; }
        ''')

    await page.evaluateOnNewDocument('''
() =>{ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); }
        ''')

    await page.evaluateOnNewDocument('''
() =>{ Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5,6], }); }
        ''')

    await page.setViewport({
        'width': 1920,
        'height': 1080})

    return page


async def main(shop_url_):
    page = await new_page()  # 实例化标签页

    # -----------------------------------------------------------------------
    await page.goto('https://www.1688.com/', {'timeout': 1000 * 60})
    await sleep(3)

    await page.evaluate('window.scrollBy(0, document.body.scrollHeight)')
    await sleep(3)

    # --------------------------------------------------------------------------
    await page.goto(shop_url_, {'timeout': 1000 * 60})

    if "login" in page.url:
        return

    await sleep(3)

    await page.evaluate('window.scrollBy(0, document.body.scrollHeight)')

    global count
    count += 1

    await sleep(3)


if __name__ == '__main__':

    shop_url = argv[1]

    while 1:
        get_blance()  # 查询余额
        check_userdir_alive()  # 清缓存

        loop = get_event_loop()

        try:
            loop.run_until_complete(main(shop_url))
        except Exception as e:
            print(e)
        finally:
            system("tskill chrome")
            print(f"绝对值刷了 {count} 次")